package com.vibeplayer.app.fragment;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SwitchCompat;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;

import com.vibeplayer.app.MainActivity;
import com.vibeplayer.app.R;
import com.vibeplayer.app.service.MusicPlayerService;
import com.vibeplayer.app.util.MediaScanner;

public class SettingsFragment extends Fragment {

    private static final String PREF_THEME = "theme_mode";
    private static final String PREF_PLAY_MODE = "play_mode";
    private static final String PREF_AUTO_SCAN_ENABLED = "auto_scan_enabled";
    private static final String PREF_CACHE_VALIDITY_PERIOD = "cache_validity_period";

    private RadioGroup themeGroup;
    private RadioGroup playModeGroup;
    private RadioGroup cacheValidityGroup;
    private SwitchCompat switchAutoScan;
    private Button btnScanNow;
    private TextView txtVersion;

    private SharedPreferences preferences;
    private MediaScanner mediaScanner;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        
        // 初始化控件
        themeGroup = view.findViewById(R.id.themeGroup);
        playModeGroup = view.findViewById(R.id.playModeGroup);
        cacheValidityGroup = view.findViewById(R.id.cacheValidityGroup);
        switchAutoScan = view.findViewById(R.id.switchAutoScan);
        btnScanNow = view.findViewById(R.id.btnScanNow);
        txtVersion = view.findViewById(R.id.txtVersion);
        
        // 获取SharedPreferences
        preferences = PreferenceManager.getDefaultSharedPreferences(requireContext());
        
        // 获取MediaScanner实例
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isServiceBound() && activity.getMusicService() != null) {
                mediaScanner = new MediaScanner(requireContext());
            }
        }
        
        try {
            PackageInfo packageInfo = requireContext().getPackageManager()
                    .getPackageInfo(requireContext().getPackageName(), 0);
            String versionName = packageInfo.versionName;
            txtVersion.setText(getString(R.string.version) + ": " + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            txtVersion.setText(getString(R.string.version) + ": 未知");
        }
        
        // 初始化主题设置
        setupThemeSettings();
        
        // 初始化自动扫描设置
        setupAutoScanSettings();
        
        // 初始化缓存有效期设置
        setupCacheValiditySettings();
        
        // 初始化播放模式设置
        setupPlayModeSettings();
        
        return view;
    }
    
    private void setupThemeSettings() {
        // 获取当前主题设置
        int currentTheme = preferences.getInt(PREF_THEME, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
        
        // 根据当前设置选中对应的单选按钮
        switch (currentTheme) {
            case AppCompatDelegate.MODE_NIGHT_NO:
                themeGroup.check(R.id.rbLightMode);
                break;
            case AppCompatDelegate.MODE_NIGHT_YES:
                themeGroup.check(R.id.rbDarkMode);
                break;
            case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
            default:
                themeGroup.check(R.id.rbSystemDefault);
                break;
        }
        
        // 设置主题选择监听器
        themeGroup.setOnCheckedChangeListener((group, checkedId) -> {
            int themeMode;
            
            if (checkedId == R.id.rbLightMode) {
                themeMode = AppCompatDelegate.MODE_NIGHT_NO;
            } else if (checkedId == R.id.rbDarkMode) {
                themeMode = AppCompatDelegate.MODE_NIGHT_YES;
            } else {
                themeMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
            }
            
            // 保存设置
            preferences.edit().putInt(PREF_THEME, themeMode).apply();
            
            // 应用主题
            AppCompatDelegate.setDefaultNightMode(themeMode);
        });
    }
    
    private void setupAutoScanSettings() {
        // 获取当前自动扫描设置
        boolean autoScanEnabled = preferences.getBoolean(PREF_AUTO_SCAN_ENABLED, true);
        
        // 设置开关状态
        switchAutoScan.setChecked(autoScanEnabled);
        switchAutoScan.setText(autoScanEnabled ? R.string.auto_scan_enabled : R.string.auto_scan_disabled);
        
        // 设置开关监听器
        switchAutoScan.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 保存设置
            preferences.edit().putBoolean(PREF_AUTO_SCAN_ENABLED, isChecked).apply();
            switchAutoScan.setText(isChecked ? R.string.auto_scan_enabled : R.string.auto_scan_disabled);
        });
        
        // 设置立即扫描按钮点击事件
        btnScanNow.setOnClickListener(v -> {
            if (mediaScanner != null) {
                Toast.makeText(requireContext(), R.string.scanning, Toast.LENGTH_SHORT).show();
                btnScanNow.setEnabled(false);
                
                // 清除缓存，强制重新扫描
                mediaScanner.clearCache();
                
                // 设置扫描完成监听器
                mediaScanner.setScanCompletedListener(songs -> {
                    requireActivity().runOnUiThread(() -> {
                        btnScanNow.setEnabled(true);
                        Toast.makeText(requireContext(), 
                                getString(R.string.scan_complete) + ": " + songs.size() + " 首歌曲", 
                                Toast.LENGTH_SHORT).show();
                    });
                });
                
                // 执行扫描
                mediaScanner.scanMediaAsync();
            }
        });
    }
    
    private void setupCacheValiditySettings() {
        // 获取当前缓存有效期设置（默认3600秒 = 1小时）
        int cacheValidityPeriod = preferences.getInt(PREF_CACHE_VALIDITY_PERIOD, 3600);
        
        // 根据当前设置选中对应的单选按钮
        if (cacheValidityPeriod <= 3600) { // 1小时
            cacheValidityGroup.check(R.id.rbOneHour);
        } else if (cacheValidityPeriod <= 10800) { // 3小时
            cacheValidityGroup.check(R.id.rbThreeHours);
        } else if (cacheValidityPeriod <= 21600) { // 6小时
            cacheValidityGroup.check(R.id.rbSixHours);
        } else if (cacheValidityPeriod <= 43200) { // 12小时
            cacheValidityGroup.check(R.id.rbTwelveHours);
        } else { // 1天或更长
            cacheValidityGroup.check(R.id.rbOneDay);
        }
        
        // 设置缓存有效期选择监听器
        cacheValidityGroup.setOnCheckedChangeListener((group, checkedId) -> {
            int validityPeriod;
            
            if (checkedId == R.id.rbOneHour) {
                validityPeriod = 3600; // 1小时
            } else if (checkedId == R.id.rbThreeHours) {
                validityPeriod = 10800; // 3小时
            } else if (checkedId == R.id.rbSixHours) {
                validityPeriod = 21600; // 6小时
            } else if (checkedId == R.id.rbTwelveHours) {
                validityPeriod = 43200; // 12小时
            } else {
                validityPeriod = 86400; // 1天
            }
            
            // 保存设置
            preferences.edit().putInt(PREF_CACHE_VALIDITY_PERIOD, validityPeriod).apply();
            
            // 如果有MediaScanner实例，清除缓存
            if (mediaScanner != null) {
                mediaScanner.clearCache();
            }
        });
    }
    
    private void setupPlayModeSettings() {
        // 获取当前播放模式设置
        int currentPlayMode = preferences.getInt(PREF_PLAY_MODE, MusicPlayerService.PLAY_MODE_NORMAL);
        
        // 根据当前设置选中对应的单选按钮
        switch (currentPlayMode) {
            case MusicPlayerService.PLAY_MODE_REPEAT_ONE:
                playModeGroup.check(R.id.rbRepeatOne);
                break;
            case MusicPlayerService.PLAY_MODE_REPEAT_ALL:
                playModeGroup.check(R.id.rbRepeatAll);
                break;
            case MusicPlayerService.PLAY_MODE_SHUFFLE:
                playModeGroup.check(R.id.rbShuffle);
                break;
            case MusicPlayerService.PLAY_MODE_NORMAL:
            default:
                playModeGroup.check(R.id.rbNormal);
                break;
        }
        
        // 设置播放模式选择监听器
        playModeGroup.setOnCheckedChangeListener((group, checkedId) -> {
            int playMode;
            
            if (checkedId == R.id.rbRepeatOne) {
                playMode = MusicPlayerService.PLAY_MODE_REPEAT_ONE;
            } else if (checkedId == R.id.rbRepeatAll) {
                playMode = MusicPlayerService.PLAY_MODE_REPEAT_ALL;
            } else if (checkedId == R.id.rbShuffle) {
                playMode = MusicPlayerService.PLAY_MODE_SHUFFLE;
            } else {
                playMode = MusicPlayerService.PLAY_MODE_NORMAL;
            }
            
            // 保存设置
            preferences.edit().putInt(PREF_PLAY_MODE, playMode).apply();
            
            // 应用播放模式
            if (getActivity() instanceof MainActivity) {
                MainActivity activity = (MainActivity) getActivity();
                if (activity.isServiceBound() && activity.getMusicService() != null) {
                    activity.getMusicService().setPlayMode(playMode);
                }
            }
        });
    }
} 